// 引入配置
import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from 'element-ui'
import store from '@/store'
// 引入路由组件
import Home from '@/views/Home'
import Search from '@/views/Search'
import Login from '@/views/Login'
import Register from '@/views/Register'
import Detail from '@/views/Detail'
import AddCartSuccess from '@/views/AddCartSuccess'
import Center from '@/views/Center'
import Pay from '@/views/Pay'
import PaySuccess from '@/views/PaySuccess'
import Trade from '@/views/Trade'

import ShopCart from '@/views/ShopCart'
Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/home',
      name: 'Home',
      component: Home,
    },
    {
      path: '/search',
      name: 'Search',
      component: Search,
    },
    {
      path: '/detail/:id',
      name: 'Detail',
      component: Detail,
    },
    {
      path: '/addcart_success',
      name: 'AddCartSuccess',
      component: AddCartSuccess,
    },
    {
      path: '/center',
      name: 'Center',
      component: Center,
    },
    {
      path: '/pay',
      name: 'Pay',
      component: Pay,
    },
    {
      path: '/paysuccess',
      name: 'PaySuccess',
      component: PaySuccess,
    },
    {
      path: '/trade',
      name: 'Trade',
      component: Trade,
    },
    {
      path: '/shopcart',
      name: 'ShopCart',
      component: ShopCart,
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
    },
    {
      path: '/register',
      name: 'Register',
      component: Register,
    },
    {
      path: '/',
      redirect: '/home',
    },
  ],
  // 每次路由跳转触发函数
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    }
  },
})

// 设置路由导航守卫
/*
  路由导航守卫：当路由跳转时触发的钩子函数
    1. 全局导航守卫（对所有路由生效）
      beforeEach
      beforeResolve
      afterEach
    2. 路由导航守卫（只对当前路由生效）
    3. 组件导航守卫（只对当前组件生效）

*/
//需要登陆才能访问得路由地址
const authList = ['/center', '/trade', '/pay', '/paysuccess']

// 全局前置导航守卫

router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  // console.log(to, from, next)
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 没有登录
    if (authList.includes(to.path)) {
      Message.error('请先登录，在访问')
      next(`/login?redirect=${to.path}`)
    } else {
      next()
    }
  }
})
// 全局后置导航守卫
// router.afterEach((to, from) => {
//   console.log(to, from)
// })

export default router

/*
    A --> B

    to代表B
    from代表A

    next 开始下一步（进行路由跳转）
      next() 相当于 next(to)，跳转到to对应路由地址
      next('/login') 或 next({ name: 'Login' })，跳转到/login
  */
